import React, { Component } from "react";
import moment from 'moment';
import {
     Icon, Table, Button, Modal, Form, Input,
    Select, Skeleton, Tag, Col, Row, AutoComplete, DatePicker, message
} from "antd";
import { getPushRecordApi, getPushTypesApi } from "../js/pushRecord";
import { cssNumber } from "jquery";

const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
class pushRecord extends Component {
    constructor(props) {
        super(props);
        this.state = {
            alertVisible: false, //提示
            confirmLoading: false,
            msg: "", //提交失败时的提示语
            tableLoading: true,
            filteredInfo: null,
            isSearch: false,
            pushRecord: [],
            pushTypes: [],
            searchData: [],
            filteredInfo2: null,
        };

    }

    componentDidMount() {
        this.refreshData();
    }

    getBeforeDayTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000;
        var beforeday = new Date(time); // 获取的是前一天日期

        beforeday = beforeday.getFullYear() + "-" + (beforeday.getMonth() + 1 > 9
            ? (beforeday.getMonth() + 1) : "0" + (beforeday.getMonth()+1)) + "-" + (beforeday.getDate() > 9
                ? (beforeday.getDate()) : "0" + (beforeday.getDate())); //字符串拼接转格式：例如2018-08-19
        
        return beforeday
    }
    getBeforeWeekTime() {
        var time = (new Date()).getTime() - 24 * 60 * 60 * 1000 * 7;
        var beforeweek = new Date(time); // 获取的是前一周日期

        beforeweek = beforeweek.getFullYear() + "-" + (beforeweek.getMonth() + 1 > 9
            ? (beforeweek.getMonth() + 1) : "0" + (beforeweek.getMonth() + 1)) + "-" + (beforeweek.getDate() > 9
                ? (beforeweek.getDate()) : "0" + (beforeweek.getDate())); //字符串拼接转格式：例如2018-08-19
        return beforeweek
    }

    refreshData() {
        let schoolId = sessionStorage.getItem("departmentId")
        let startTime = moment(this.getBeforeWeekTime()).format('YYYY-MM-DD')
        let endTime = moment(this.getBeforeDayTime()).format('YYYY-MM-DD')
        this.getPushTypes(schoolId)
        this.getPushRecord(schoolId, null, startTime, endTime, null)
    }

    getPushTypes(schoolId) {
        getPushTypesApi(schoolId).then((res) => {
            this.setState({
                pushTypes: res.data
            })
        })
    }


    getPushRecord(schoolId, pushUserName = null, startTIme = null, endTime = null, pushTypes = null) {
        getPushRecordApi(schoolId, pushUserName, startTIme, endTime, pushTypes).then((res) => {
            let pushRecord = []
            res.data.forEach((item, index) => {
                pushRecord.push({
                    key: index + 1,
                    pushUserName: item.pushUserName,
                    pushTime: item.pushTime,
                    pushType: item.pushType
                })
            })
            this.setState({
                pushRecord: pushRecord,
                tableLoading: false
            })
        })
    }

    searchSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if(values.pushTime.length == 0) {
                    message.error('请选择推送时间')
                } else {
                    let schoolId = sessionStorage.getItem("departmentId")
                    let pushUserName = values.pushUserName
                    let startTIme
                    let endTime
                    let pushTypes = values.pushTypes
                    console.log("valus", values)
                    if(values.pushTime.length != 0) {
                        startTIme = moment(values.pushTime[0]).format('YYYY-MM-DD')
                        endTime = moment(values.pushTime[1]).format('YYYY-MM-DD')
                    }
                    this.getPushRecord(schoolId, pushUserName, startTIme, endTime, pushTypes)
                }
        })
    }

    handleSearch = (selectedKeys, confirm) => () => {
        confirm();
    }

    handleSearchReset = clearFilters => () => {
        clearFilters();
    }

    handleChange = (pagination, filters, sorter) => () => {
        this.setState({
            filteredInfo: filters,
            sortedInfo: sorter,
        });
    }




    render() {

        let pushTypeOptions = []
        if(this.state.pushTypes.length != 0) {
            pushTypeOptions = this.state.pushTypes.map((d, index) => 
                <Option value={d} key={index}>{d}</Option>
            )
        }
        let { sortedInfo, filteredInfo } = this.state;
        sortedInfo = sortedInfo || {};
        filteredInfo = filteredInfo || {};
        const columns = [{
            title: "序号",
            dataIndex: "key",
            key: "key"
        },
        {
            title: "推送用户",
            dataIndex: "pushUserName",
            key: "pushUserName",
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.pushUserName.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "推送时间",
            dataIndex: "pushTime",
            sorter: (a, b) => new Date(a.pushTime).getTime() - new Date(b.pushTime).getTime(),
        }, {
            title: "推送类型",
            dataIndex: "pushType",
            key: "pushType",
        }];

        const { getFieldDecorator, getFieldValue } = this.props.form;
        let { sortedInfo2, filteredInfo2 } = this.state;
        sortedInfo2 = sortedInfo2 || {};
        filteredInfo2 = filteredInfo2 || {};


        let keyWidth = undefined;
        let pushUserNamethWidth = undefined;
        let pushTimeWidth = undefined;
        let pushTypeWidth = undefined;

        let winWidth;
        // 获取窗口宽度
        if (window.innerWidth){
            winWidth = window.innerWidth;
            console.log("width", winWidth)}
        else if ((document.body) && (document.body.clientWidth))
            winWidth = document.body.clientWidth;
        if (winWidth <= 1536) {
            keyWidth = 60;
            pushUserNamethWidth = 120;
            pushTimeWidth = 100;
            pushTypeWidth = 120;
            
        }

        const columnsSearch = [{
            title: "序号",
            dataIndex: "key",
            key: "key",
            width: keyWidth,
        }, {
            title: "推送用户",
            dataIndex: "pushUserName",
            key: "pushUserName",
            width: pushUserNamethWidth,
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div className="custom-filter-dropdown">
                    <Input
                        ref={ele => this.searchInput = ele}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={this.handleSearch2(selectedKeys, confirm)}
                    />
                    <Button type="primary" onClick={this.handleSearch2(selectedKeys, confirm)}>查找</Button>
                    <Button onClick={this.handleSearchReset2(clearFilters)}>重置</Button>
                </div>
            ),
            filterIcon: filtered => <Icon type="search" style={{ color: filtered ? '#108ee9' : '#aaa', fontSize: '1.2em' }} />,
            onFilter: (value, record) => record.pushUserName.toLowerCase().includes(value.toLowerCase()),
            onFilterDropdownVisibleChange: (visible) => {
                if (visible) {
                    setTimeout(() => {
                        this.searchInput.focus();
                    });
                }
            }
        }, {
            title: "推送时间",
            dataIndex: "pushTime",
            key: "pushTime",
            width: pushTimeWidth,
            sorter: (a, b) => new Date(a.pushTime).getTime() - new Date(b.pushTime).getTime(),
        },  {
            title: '推送类型',
            dataIndex: 'pushType',
            key: 'pushType',
            width: pushTypeWidth
        }];


        let labelCol = {
            sm: { span: 6 },
            xl: { span: 6 },
            xxl: { span: 5 },
        };

        let wrapperCol = {
            sm: { span: 18 },
            xl: { span: 18 },
            xxl: { span: 19 },
        };

        return (
            <div style={{ marginBottom: 16 }}>
                <Form
                    style={{
                        padding: '12px',
                        backgroundColor: '#fafafa',
                        borderRadius: 8,
                        marginBottom: 16,
                    }}
                    layout="inline"
                    onSubmit={this.searchSubmit}>
                    <Row>
                        <Col span={8}>
                            <FormItem
                                label="推送用户"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("pushUserName", {
                                    rules: [{
                                        required: false,
                                    }]
                                })(
                                    <AutoComplete
                                        allowClear={true}
                                        style={{ width: '100%' }}
                                        dataSource={this.state.classNameArr}
                                        placeholder="请输入推送用户"
                                        filterOption={(inputValue, option) => option.props.children.toUpperCase().indexOf(inputValue.toUpperCase()) !== -1}
                                    />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="推送时间"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("pushTime", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }],
                                    initialValue: [ // 核心代码
                                        moment(this.getBeforeWeekTime(), 'YYYY-MM-DD'),
                                        moment(this.getBeforeDayTime(), 'YYYY-MM-DD'),
                                      ],
                                })(
                                    <RangePicker
                                        style={{ width: '100%' }}
                                        format="YYYY-MM-DD" />
                                )}
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem
                                label="推送类型"
                                style={{ width: '100%' }}
                                labelCol={labelCol}
                                wrapperCol={wrapperCol}>
                                {getFieldDecorator("pushTypes", {
                                    rules: [{
                                        type: 'array',
                                        required: false,
                                    }]
                                })(
                                    <Select
                                        style={{ width: '100%' }}
                                        mode="multiple"
                                        placeholder="请选择推送类型(可多选)">
                                        {pushTypeOptions}
                                    </Select>
                                )}
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <FormItem
                            style={{ float: 'right' }}>
                            <Button type="primary" htmlType="submit">搜索</Button>
                            <Button style={{ marginLeft: 8 }} onClick={this.searchReset}>清空</Button>
                        </FormItem>
                    </Row>
                </Form>
                {this.state.isSearch ? (
                    <div>
                        <div style={{
                            marginBottom: 16,
                            padding: 16,
                            width: '100%',
                            height: 300,
                            border: '1px solid',
                            borderColor: '#f5f5f5'
                        }}>
                        </div>
                        <Table
                            dataSource={this.state.searchData}
                            columns={columnsSearch}
                            loading={this.state.tableLoading}
                            locale={{ emptyText: '暂无数据' }}
                            rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                            onChange={this.handleChange}
                            pagination={{  //分页
                                total: this.state.searchData.length, //数据总数量
                                defaultPageSize: 10, //默认显示几条一页
                                //pageSize: 10,
                                showTotal: function (total) {  //设置显示一共几条数据
                                    return '共 ' + total + ' 条数据';
                                },
                                showSizeChanger: true,
                                showQuickJumper: true,
                                pageSizeOptions: [5, 10, 20, 30]
                            }} />
                    </div>
                ) : (
                    <Table
                        dataSource={this.state.pushRecord}
                        columns={columns}
                        loading={this.state.tableLoading}
                        locale={{ emptyText: '暂无数据' }}
                        rowClassName={(record, index) => index % 2 === 0 ? "rowOne" : "rowTwo"}
                        pagination={{  //分页
                            total: this.state.pushRecord.length, //数据总数量
                            defaultPageSize: 10, //默认显示几条一页
                            //pageSize: 10,
                            showTotal: function (total) {  //设置显示一共几条数据
                                return '共 ' + total + ' 条数据';
                            },
                            showSizeChanger: true,
                            showQuickJumper: true,
                            pageSizeOptions: [5, 10, 20, 30]
                        }} />
                )}
            </div>
        )
    }
}
const PushRecord = Form.create()(pushRecord);

export { PushRecord }